package com.xie.authority_system.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.xie.authority_system.config.security.exception.CustomAuthenticationException;
import com.xie.authority_system.utils.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 登录失败处理器
 *
 * @author 谢金成
 * @date 2024/1/8 16:32
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 设置响应编码格式
        response.setContentType("application/json;charset=utf-8");
        // 获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        // 定义变量, 保存异常信息
        String message = null;
        // 定义状态码
        int code = 500;

        if (exception instanceof AccountExpiredException) {
            message = "账户过期, 登录失败!";
        } else if (exception instanceof BadCredentialsException) {
            message = "用户名或密码错误, 登录失败!";
        } else if (exception instanceof CredentialsExpiredException) {
            message = "密码过期, 登录失败!";
        } else if (exception instanceof DisabledException) {
            message = "账户被禁用, 登录失败!";
        } else if (exception instanceof LockedException) {
            message = "账户被锁, 登录失败!";
        } else if (exception instanceof InternalAuthenticationServiceException) {
            message = "账户不存在, 登录失败!";
        } else if (exception instanceof CustomAuthenticationException) {
            message = exception.getMessage();
            code = 600;
        } else {
            message = "登录失败!";
        }

        // 将结果转换为JSON
        String result = JSON.toJSONString(Result.error().code(code).message(message));

        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
